import superService from "./superService";
import O1HD, { services } from "../gameEngine";
import gameConfig from "../configs/gameConfig";
import data_control from "../libs/data_control";
import { GAME_MODE } from "../managers/gameContent/gameMode_json";
import { IGameModeNumberMap } from "../../Game/Interface";
import coin from "../../O1ModuleRes/control/coin";

interface WEB_USER_INFO {
  m_devilCurrLevel: number;
  m_coins: number;
  m_unlockStamp: number;
  m_synthesisEquipmentList: string[];
}

export enum MEMBERTYPE {
  //钻石
  DIAMOND,
  //王者
  KING,
}

export enum BARDGEANITYPE {
  //钻石待机
  DIAMONDSTAND = "DiamondStand",
  //钻石打开
  DIAMONDOPEN = "DiamondArise",
  //王者待机
  KINGSTAND = "KingStand",
  //王者打开
  KINGOPEN = "Switch",
}

export default class userService extends superService {
  protected className: string = "用户服务";

  //观看广告恢复体力
  private m_constAddOncePower: number;
  //恢复体力 单位 : 秒(s)
  private m_constResetPowerTime: number;
  //恢复体力 参数
  private m_constResetPowerValue: number;
  //
  private m_constAddOnceCoins: number;
  //最大体力
  private m_powerMax: number;
  //体力
  private m_power: number;
  private m_normalPower: number;
  //金币
  private m_coins: number;
  private m_normalCoins: number;
  private m_unlockLevel: number;
  //游戏初始时间
  private m_firstPlayerTime: number;

  private unlock_all_level_flag:boolean = false;

  // 解锁过的模式
  private m_unlockModes: number[] = [];

  private m_modeAdCount: IGameModeNumberMap = <IGameModeNumberMap>{};
  //
  private readonly COINS_KEY: string = "user-coins";
  private readonly POWER_KEY: string = "user-power";
  private readonly UNLOCK_KEY: string = "user-unlock";
  private readonly POWER_TIME_KEY: string = "user-power-time";
  private readonly FIRST_PLAY_KEY: string = "user-first-play";

  private readonly UNLOCK_MODE: string = "user-unlock-mode";
  private readonly MODE_ADCOUNT_KEY = "user-mode-adCount";

  private readonly LAST_LOGIN_DATE_KEY : string = "user-last-login-date";

  private readonly InfinityModel: string = 'user-is-infinity';
  
  private readonly InfinityPower_Time_Key: string = 'user-logintime';

  private readonly Level_UnlockAll_key:string = "user-level-unlock-all-key";

  private readonly Level_UnlockAll_Time_Key:string = "user-level-unlock-all-time-key";

  /**第一次登陆的key */
  private readonly first_Login_key:string = "user-first-login-key";

  /**额外送一个免广告币的key */
  private readonly extra_ad_key:string = "user-extra-ad-key";

  //
  m_currLoginCode: string = null;
  //
  m_UniqueId: string = null;
  //
  private m_curWebUserInfo: WEB_USER_INFO = null;

  constructor() {
    super();
  }

  async loadService(): Promise<void> {
    await super.loadService();
    this.onInitNormalData(
      gameConfig.MAX_POWER,
      gameConfig.NORMAL_POWER,
      gameConfig.NORMAL_COINS,
      gameConfig.ADD_ONCE_POWER,
      gameConfig.REST_POWER_TIME,
      gameConfig.REST_POWER_VALUE,
      gameConfig.ADD_ONCE_COINS
    );
    //
    // this.onWebInfoUpdate();
    return Promise.resolve();
  }

  /**
   * 是否在新手保护的时间内
   * @returns
   */
  isFirstPlayerTimeIn() {
    return (
      Date.now() - this.m_firstPlayerTime < gameConfig.FIRST_VIDEO_TIME * 1000
    );
  }

  onInitNormalData(
    maxPower: number,
    normalPower: number,
    normalCoins: number,
    addOncePower: number,
    restPowerTime: number,
    restPowerValue: number,
    addOnceCoins: number
  ) {
    this.m_powerMax = maxPower;
    this.m_normalPower = normalPower;
    this.m_normalCoins = normalCoins;
    this.m_constAddOncePower = addOncePower;
    this.m_constResetPowerTime = restPowerTime;
    this.m_constResetPowerValue = restPowerValue;
    this.m_constAddOnceCoins = addOnceCoins;
    //
    this.loadUserData();
  }

  getFirstLogin(){
    return O1HD.getServices().localStorageSrv.getStorage(this.first_Login_key);
  }

  setFirstLogin(num){
    O1HD.getServices().localStorageSrv.setStorage(this.first_Login_key,num);
  }

  getExtraAd(){
      return O1HD.getServices().localStorageSrv.getStorage(this.extra_ad_key);
  }

  
  setExtraAd(num){
    O1HD.getServices().localStorageSrv.setStorage(this.extra_ad_key,num);
}

  getResetPowerTime() {
    return this.m_constResetPowerTime;
  }

  getResetPowerValue() {
    return this.m_constResetPowerValue;
  }

  getInfinityPower(){
    return O1HD.getServices().localStorageSrv.getStorage(this.InfinityModel) == "1";
  }

  setInfinity(infinityNum:number){
    O1HD.getServices().localStorageSrv.setStorage(this.InfinityModel,infinityNum);
  }

  getInfinityTime(){
    return O1HD.getServices().localStorageSrv.getStorage(this.InfinityPower_Time_Key);
  }

  setInfinityTime(){
    O1HD.getServices().localStorageSrv.setStorage(this.InfinityPower_Time_Key, data_control.getCurrDateDayString());
  }

  loadLevelAllUnlockFlag(){
    let str = O1HD.getServices().localStorageSrv.getStorage(this.Level_UnlockAll_key) || "false";
    this.unlock_all_level_flag = JSON.parse(str);
    this.writeLevelAllUnlockFlag();
  }

  getLevelAllUnlockFlag(){
    return this.unlock_all_level_flag;
  }

  setLevelAllUnlockFlag(flag:boolean){
    this.unlock_all_level_flag = flag;
    this.writeLevelAllUnlockFlag();
  }

  writeLevelAllUnlockFlag(){
    O1HD.getServices().localStorageSrv.setStorage(this.Level_UnlockAll_key, this.unlock_all_level_flag);
  }

  getLevelAllUnlockTime(){
    let str = O1HD.getServices().localStorageSrv.getStorage(this.Level_UnlockAll_Time_Key) || "0";
    let time = JSON.parse(str);
    if(isNaN(time)){
      time = 0;
    }
    return time;
  }

  setLevelAllUnlockTime(){
    O1HD.getServices().localStorageSrv.setStorage(this.Level_UnlockAll_Time_Key, Date.now());
  }

  setCoins(coins: number, isPlus: boolean) {
    if (isPlus) {
      coins = this.m_coins + coins;
      if(coins > 0){
        O1HD.getManagers().soundMgr.playSound("mainSound/GetCoin");
      }
    }
    this.m_coins = data_control.getValueOfAreaMinMax(
      coins,
      0,
      Number.MAX_VALUE
    );
    this.writeCoins();
  }

  getCoins() {
    return this.m_coins;
  }

  setPower(
    power: number,
    isPlus: boolean,
    isCanBeyond?: boolean,
    isReset: boolean = false
  ) {
    if (isPlus) {
      power = this.m_power + power;
    }
    //满的开始扣
    if (this.m_powerMax == this.m_power && power == this.m_power - 1) {
      isReset = true;
    }
    if (isCanBeyond) {
      this.m_power = data_control.getValueOfAreaMinMax(power, 0, 9999);
    } else {
      // if (this.m_power < this.m_powerMax) {
      this.m_power = data_control.getValueOfAreaMinMax(
        power,
        0,
        this.m_powerMax
      );
      // }
    }
    this.writePower(isReset);
  }

  getMaxPower() {
    return this.m_powerMax;
  }

  getNormalPower() {
    return this.m_normalPower;
  }

  getPower() {

    if (isNaN(Number(this.m_power))) {
      console.info("获取体力异常归零", this.m_power)
      O1HD.getServices().localStorageSrv.setStorage(this.POWER_KEY, 0);
      this.m_power = 0
    }
    return this.m_power;
  }

  getMemberStatus() {
    let ms =
      O1HD.getServices().localStorageSrv.getStorage("private-member-type") ||
      "0";
    return Number(ms);
  }

  setMemberStatus(type: number = 0) {
    O1HD.getServices().localStorageSrv.setStorage("private-member-type", type);
    O1HD.getServices().localStorageSrv.setStorage(
      "user-membertime",
      Date.now()
    );
  }

  //看广告添加体力
  addPowerOfVideo() {
    //
    this.setPower(this.m_constAddOncePower, true, true);
  }

  getConstAddOncePower() {
    return this.m_constAddOncePower;
  }

  setUnlockLevel(unlockLevel: number, isPlus: boolean) {
    if (isPlus) {
      unlockLevel = this.m_unlockLevel + unlockLevel;
    }
    this.m_unlockLevel = unlockLevel;
    this.writeUnLockLevel();
  }

  getUnlockLevel() {
    return this.m_unlockLevel;
  }

  //回复体力倒计时
  getPowerResetTimer(): number {
    let dateNow = Date.now();
    let dateOld =
      O1HD.getServices().localStorageSrv.getStorage(this.POWER_TIME_KEY) ||
      dateNow;
    return (
      this.m_constResetPowerTime - Math.floor((dateNow - Number(dateOld)) / 1e3)
    );
  }

  onPowerTimerReset(): boolean {
    //计算体力恢复
    let dateNow = Date.now();
    let dateOld =
      O1HD.getServices().localStorageSrv.getStorage(this.POWER_TIME_KEY) ||
      dateNow;
    dateOld = Number(dateOld);
    let restCount = Math.floor(
      (dateNow - dateOld) / (this.m_constResetPowerTime * 1000)
    );
    //
    let addHp = restCount * this.m_constResetPowerValue;
    if (addHp && this.getPower() < this.m_powerMax) {
      this.setPower(addHp, true, false, true);
      return true;
    }
    return false;
  }

  UnlockMode(mode: GAME_MODE) {
    if (!this.getModeUnlocked(mode)) {
      this.m_unlockModes.push(mode);
      this.writeUnlockMode();
    }
  }

  getModeUnlocked(mode: GAME_MODE): boolean {
    return (
      this.m_unlockModes.includes(mode) ||
      gameConfig.MODE_VIDEO_COUNT[mode] == 0
    );
  }

  addModeAdCount(mode: GAME_MODE) {
    this.m_modeAdCount[mode]++;
    this.writeModeAdCount();
  }

  getModeAdCount(mode: GAME_MODE): number {
    return this.m_modeAdCount[mode];
  }

  loadUser() {
    //
    this.loadNameAndHead();
  }

  private loadFirstPlayerTime() {
    this.m_firstPlayerTime = Number(
      O1HD.getServices().localStorageSrv.getStorage(this.FIRST_PLAY_KEY) || "0"
    );
    if (this.m_firstPlayerTime == 0) {
      this.m_firstPlayerTime = Date.now();
      this.writeFirstPlayerTime();
    }
  }

  private writeFirstPlayerTime() {
    O1HD.getServices().localStorageSrv.setStorage(
      this.FIRST_PLAY_KEY,
      this.m_firstPlayerTime
    );
  }

  private loadUserData() {
    this.loadCoins();
    this.loadPower();
    this.loadUnlockLevel();
    this.loadFirstPlayerTime();
    this.loadUnlockMode();
    this.loadModeAdCount();
    //
    this.loadNameAndHead();
    this.loadLevelAllUnlockFlag();
  }

  setLastLoginDate(){
    O1HD.getServices().localStorageSrv.setStorage(this.LAST_LOGIN_DATE_KEY, data_control.getCurrDateDayString());
  }

  getLastLoginDate(){
    return O1HD.getServices().localStorageSrv.getStorage(this.LAST_LOGIN_DATE_KEY);
  }

  private loadModeAdCount() {
    this.m_modeAdCount = {
      0: 0,
      1: 0,
      3: 0,
      4: 0,
      5: 0,
      6: 0,
      7: 0,
      8: 0,
    };
    //TODO 新模式请看这里
    if (O1HD.getServices().localStorageSrv.getStorage(this.MODE_ADCOUNT_KEY)) {
      let object: IGameModeNumberMap = JSON.parse(
        O1HD.getServices().localStorageSrv.getStorage(this.MODE_ADCOUNT_KEY)
      );
      for (const key in object) {
        if (Object.prototype.hasOwnProperty.call(object, key)) {
          const element = object[key];
          this.m_modeAdCount[key] = element;
        }
      }
    }
  }

  private writeModeAdCount() {
    services().localStorageSrv.setStorage(
      this.MODE_ADCOUNT_KEY,
      JSON.stringify(this.m_modeAdCount)
    );
  }

  private loadUnlockMode() {
    let dataStr: string = O1HD.getServices().localStorageSrv.getStorage(
      this.UNLOCK_MODE
    );
    if (dataStr) {
      this.m_unlockModes = JSON.parse(dataStr);
      // console.warn(this.m_unlockModes);
    }
  }

  private writeUnlockMode() {
    services().localStorageSrv.setStorage(
      this.UNLOCK_MODE,
      JSON.stringify(this.m_unlockModes)
    );
  }

  private loadUnlockLevel() {
    this.m_unlockLevel = Number(
      O1HD.getServices().localStorageSrv.getStorage(this.UNLOCK_KEY) || 0
    );
  }

  private writeUnLockLevel() {
    O1HD.getServices().localStorageSrv.setStorage(
      this.UNLOCK_KEY,
      this.m_unlockLevel
    );
  }

  private loadCoins() {
    this.m_coins =
      Number(
        O1HD.getServices().localStorageSrv.getStorage(this.COINS_KEY) || 0
      ) || this.m_normalCoins;
  }

  private loadPower() {
    let powerStr = O1HD.getServices().localStorageSrv.getStorage(
      this.POWER_KEY
    );
    if (isNaN(Number(powerStr))) {
      console.info("初始异常归零", powerStr)
      O1HD.getServices().localStorageSrv.setStorage(this.POWER_KEY, 0);
      powerStr = "0"
    }

    if (powerStr === "" || powerStr === null) this.m_power = this.m_normalPower;
    else this.m_power = Number(powerStr);
    //体力恢复
    this.onPowerTimerReset();
  }

  private writeCoins() {
    //
    O1HD.getServices().localStorageSrv.setStorage(this.COINS_KEY, this.m_coins);
  }

  private writePower(isReset: boolean) {
    //
    O1HD.getServices().localStorageSrv.setStorage(this.POWER_KEY, this.m_power);
    let nil = services().localStorageSrv.getStorage(this.POWER_TIME_KEY);
    if (isReset || !nil) {
      let dateNow = Date.now();
      O1HD.getServices().localStorageSrv.setStorage(
        this.POWER_TIME_KEY,
        dateNow
      );
    }
  }

  private loadNameAndHead() {
    //
    // return;
    //
    let currMiniApp = O1HD.getServices().miniGameSrv.getAppApiInstance();
    //
    let fail = () => {
      currMiniApp.showToast({ title: "登录失败" });
    };
    //已登录
    // if (this.m_currLoginCode) return;
    //登录
    currMiniApp.login({
      force: false,
      success: (res) => {
        // this.m_currLoginCode = res.code;
        //授权
        currMiniApp.authorize({
          success: () => {
            //信息获取
            currMiniApp.getUserInfo({
              success: (res) => {
                // this.m_name = res.userInfo.nickName;
                // this.m_headImage = res.userInfo.avatarUrl;
              },
              fail,
            });
          },
          fail,
        });
        // //获取唯一ID
        // if (this.m_UniqueId) {
        //     return;
        // }
        // //
        // gameHttp_module.getUserWxIdentifyByCode(this.m_currLoginCode, (res) => {
        //     console.debug('我的唯一ID', res);
        //     this.m_UniqueId = res;
        //     gameHttp_module.getUserWebInfo(this.m_UniqueId, (res) => {
        //         this.m_curWebUserInfo = JSON.parse(res);
        //         console.debug('读取到的数据', res);
        //         this.onWebInfoGetOnce();
        //     }, res1 => {
        //         this.m_curWebUserInfo = {
        //             m_coins: this.m_normalCoins,
        //             m_devilCurrLevel: 0,
        //             m_synthesisEquipmentList: [],
        //             m_unlockStamp: 0,
        //         }
        //     });
        // })
      },
      fail,
    });
  }

  private onWebInfoUpdate() {
    setInterval(() => {
      if (this.m_UniqueId == null || this.m_curWebUserInfo == null) return;
      for (let key in this.m_curWebUserInfo) {
        this.m_curWebUserInfo[key] = this[key];
      }
      console.log("更新数据", this.m_UniqueId, this.m_curWebUserInfo);
    }, 3e3);
  }

  private onWebInfoGetOnce() {
    //没有线上
    if (this.m_UniqueId == null || this.m_curWebUserInfo == null) return;
    //如果经验金币都有，就说明读到了
    if (this.m_coins != this.m_normalCoins) return;
    console.log("获取数据", this.m_curWebUserInfo);
    //
    for (let key in this.m_curWebUserInfo) {
      this[key] = this.m_curWebUserInfo[key];
    }
  }
}
